/**
 * @file MutexLock.hpp
 * @brief 互斥锁封装类的声明
 * @details 封装了pthread_mutex，提供RAII风格的锁管理
 */

#ifndef __MutexLock_HPP__
#define __MutexLock_HPP__

#include "Noncopyable.hpp"

#include <pthread.h>

namespace wd
{

/**
 * @class MutexLock
 * @brief 互斥锁类
 * @details 封装pthread_mutex_t，不可复制
 */
class MutexLock : Noncopyable
{
public:
    MutexLock();
    ~MutexLock();

    /**
     * @brief 加锁
     */
    void lock();
    
    /**
     * @brief 解锁
     */
    void unlock();

    /**
     * @brief 获取互斥锁指针
     * @return pthread_mutex_t指针
     */
    pthread_mutex_t * getMutexLockPtr() {   return &_mutex; }

private:
    pthread_mutex_t _mutex;  ///< 互斥锁
};

/**
 * @class MutexLockGuard
 * @brief RAII风格的互斥锁守卫
 * @details 构造时自动加锁，析构时自动解锁
 */
class MutexLockGuard
{
public:
    /**
     * @brief 构造时加锁
     * @param m MutexLock引用
     */
    MutexLockGuard(MutexLock & m)
    : _mutex(m)
    {
        _mutex.lock();
    }

    /**
     * @brief 析构时解锁
     */
    ~MutexLockGuard()
    {
        _mutex.unlock();
    }

private:
    MutexLock & _mutex;  ///< 互斥锁引用
};


#if 0
//不是inline函数
void MutexLock::lock()
{
    pthread_mutex_lock(&_mutex);
}
#endif



}//end of namespace wd


#endif

